package services

import (
	"fmt"
	"github.com/prometheus/common/log"
	"github.com/zw2582/zm_go_lib/helpers"
	"kitalk/models"
	"time"
)

//Error 记录错误，区分部分错误可返回给客户自己
func (this *MessageService) Error(msg string, err error) {
	log.Error(fmt.Sprintf("msg:%s,uid:%d err:%s \nWsMessage:%+v", msg, this.client.User.Id, err.Error(), this.msg))

	data := helpers.HArr{
		"msg" : err.Error(),
	}

	//推送错误给自己
	this.client.WriteReturn(RESP_ERROR, data)
}

//SendChartRecord 发送聊天记录到客户端
func (this *MessageService) SendChartRecord(chartRecord models.ChartRecord, uids ...uint) error {
	//获取用户信息
	user := models.UserGet(chartRecord.Uid)
	data := helpers.HArr{
		"uindex":user.UUID,
		"uface":user.Avatar,
		"uname":user.Name,
		"date":PrettyCreatedAt(chartRecord.CreatedAt),
		"content":chartRecord.Content,
		"record_id":chartRecord.Id,
	}

	//没有推送用户则发送给自己
	if len(uids) == 0 {
		this.client.WriteReturn(RESP_MESSAGE, data)
		return nil
	}

	//有推送用户发送给用户
	for _, uid := range uids {
		UserClientService.WriteMessage(uid, RESP_MESSAGE, data)
	}
	return nil
}

//SendChartRecord 发送顾客接洽通知
func (this *MessageService) SendChartManager(chartManager models.ChartManager, uids ...uint) error {
	data := helpers.HArr{
		"id":chartManager.Id,
		"chart_id":chartManager.ChartId,
	}

	//没有推送用户则发送给自己
	if len(uids) == 0 {
		this.client.WriteReturn(RESP_JIEQIA, data)
		return nil
	}

	//有推送用户发送给用户
	for _, uid := range uids {
		UserClientService.WriteMessage(uid, RESP_JIEQIA, data)
	}
	return nil
}

//PrettyCreatedAt 美化创建时间
func PrettyCreatedAt(created_at time.Time) string {
	now := time.Now() //现在时间
	//如果发表时间离现在时间不到一分钟显示“刚刚”
	dura := now.Sub(created_at)
	if dura < time.Minute {
		return `刚刚`
	}
	//如果发表时间不到一个小时，则显示“x分钟前”
	if dura < time.Hour {
		return fmt.Sprintf("%d分钟前", int(dura.Minutes()))
	}
	//如果发表时间不到一天，则显示“x小时前”
	if dura < time.Hour * 24 {
		return fmt.Sprintf("%d小时前", int(dura.Hours()))
	}
	//如果发表时间大于1天，但小于2天，则显示“昨天”
	if dura < time.Hour * 48 {
		return "昨天"
	}
	//如果发表时间小于3天，则显示“前天”
	if dura < time.Hour * 72 {
		return "前天"
	}
	//其余的显示日期格式
	return created_at.Format("2006-01-02")
}